<template>
  <el-container
    v-loading="loading"
    :class="{ 'is-perview': isPreview }"
    class="wk-print-container">
    <el-header>
      <template v-if="isPreview">
        <el-button type="primary" @click="handleClick('download')">{{ `${perviewTypeName} 下载` }}</el-button>
        <el-button type="primary" @click="handleClick('print')">打印</el-button>
        <el-button @click="handleClick('goback')">取消</el-button>
      </template>
      <template v-else>
        <span class="select-label">选择模板</span>
        <el-select
          v-model="templateId"
          style="width: 170px;"
          class="handle-item-content"
          @change="getDetail">
          <el-option
            v-for="item in templateOptions"
            :key="item.templateId"
            :label="item.templateName"
            :value="item.templateId" />
        </el-select>
        <span class="select-label">类型</span>
        <el-select
          v-model="perviewType"
          style="width: 80px;"
          class="handle-item-content">
          <el-option
            v-for="item in previewOptions"
            :key="item"
            :label="item"
            :value="item" />
        </el-select>

        <el-tooltip
          v-if="perviewType === 'word'"
          effect="dark"
          content="word模板格式暂不支持水印功能"
          placement="bottom">
          <i class="wk wk-icon-fill-help wk-help-tips" />
        </el-tooltip>
        <el-button class="preview-button" type="primary" @click="printPreviewClick">打印预览</el-button>
      </template>
    </el-header>
    <el-main>
      <div class="main-container">
        <div v-show="isPreview" class="main-content">
          <iframe
            id="wkPrint"
            :height="iframeHeight"
            :src="iframeUrl"
            style="width: 100%;height: calc(100% - 100px);margin-top: 54px;"
            scrolling="no"
            frameborder="0" />
        </div>
        <div v-show="!isPreview" class="main-tips">您可以在当前页面对模板文字进行调整，确认无误后可进行打印</div>
        <div v-show="!isPreview" class="main-content">
          <tinymce
            ref="editor"
            v-model="content"
            :toolbar="toolbar"
            :plugins="plugins"
            :height="richHeight"
            :init="{
              statusbar: false,
              extended_valid_elements: 'span[class|title|wktag|style|contenteditable]',
              content_style: 'p { margin: 5px 0; line-height: 1.5;}',
              content_css: ['./static/tinymce/css/tiny-wk-word.css'],
            }"
            is-print
            class="rich-txt" />
        </div>
      </div>
    </el-main>
  </el-container>
</template>

<script>
import {
  oaExaminePrintTemplatePrintAPI,
  // printRecordDetailAPI,
  oaExaminePrintTemplateListAPI,
  oaExaminePrintTemplatePreviewAPI
} from '@/api/admin/oa'
import { crmFileDownByPathAPI, downloadFileAPI } from '@/api/common'

import Tinymce from '@/components/Tinymce'
import Toolbar from '@/components/Tinymce/toolbar'
import Plugins from '@/components/Tinymce/plugins'

import { downloadFileWithBuffer } from '@/utils'

export default {
  name: 'Print',
  components: {
    Tinymce
  },
  beforeRouteUpdate(to, from, next) {
    this.content = ''
    next()
  },
  props: {},
  data() {
    return {
      loading: false,
      isPreview: false, // 是编辑 还是打印预览
      templateOptions: [],
      templateId: '',
      typeId: '', // 模块对应的id
      previewOptions: ['pdf', 'word'],
      perviewType: 'pdf',
      content: '',
      historyData: null,
      richHeight: document.documentElement.clientHeight - 152,

      // 预览
      iframeUrl: '',
      iframeHeight: document.documentElement.clientHeight - 170,
      srcData: null,
      toolbar: `${Toolbar} | watermark | signature signature-top signature-bottom signature-left signature-right`,
      plugins: `${Plugins} watermark signature`
    }
  },
  computed: {
    perviewTypeName() {
      return {
        word: 'Word',
        pdf: 'PDF'
      }[this.perviewType]
    },
    queryParams() {
      return this.$route.query
    }
  },
  created() {
    // 去除打印
    this.toolbar = this.toolbar.replace('print ', '')
    this.plugins = this.plugins.replace('print ', '')

    if (this.queryParams.type == 'history') {
      // this.getRecordDetail()
    } else {
      this.typeId = this.queryParams.id
      this.getTemplateOptions(this.queryParams.templateId)
    }

    window.addEventListener('resize', this.changeIframeHeight)
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.changeIframeHeight)
  },
  methods: {
    changeIframeHeight() {
      this.iframeHeight = document.documentElement.clientHeight - 170
    },

    /**
     * 获取模板配置
     */
    getTemplateOptions(templateId) {
      this.loading = true
      oaExaminePrintTemplateListAPI({
        configId: templateId,
        pageType: 0
      })
        .then(res => {
          this.templateOptions = res.data.list || []
          if (this.queryParams.type != 'history') {
            if (this.templateOptions.length) {
              this.templateId = this.templateOptions[0].templateId
              this.getDetail()
            } else {
              this.templateId = ''
            }
          }

          this.loading = false
        })
        .catch(() => {
          this.loading = false
        })
    },

    /**
     * 详情
     */
    getDetail() {
      this.loading = true
      oaExaminePrintTemplatePrintAPI({
        templateId: this.templateId,
        id: this.typeId
      })
        .then(res => {
          this.loading = false
          const hasValues = !!this.content
          this.content = res.data
          if (hasValues) {
            this.$nextTick(() => {
              this.$refs.editor.updateIframeHeight()
            })
          }
        })
        .catch(() => {
          this.loading = false
        })
    },

    /**
     * 详情
     */
    // getRecordDetail() {
    //   this.loading = true
    //   printRecordDetailAPI({
    //     recordId: this.queryParams.recordId
    //   })
    //     .then(res => {
    //       this.loading = false
    //       const data = res.data || {}
    //       this.historyData = data
    //       this.templateId = data.templateId
    //       this.typeId = data.typeId

    //       this.getTemplateOptions(data.crmType)
    //       this.content = data.recordContent || ''
    //     })
    //     .catch(() => {
    //       this.loading = false
    //     })
    // },

    /**
       * 打印
       */
    compactPrint() {
      this.$refs.editor.editor.execCommand('mcePrint')
      // this.savePrintRecord()
    },

    /**
     * 打印预览
     */
    printPreviewClick() {
      this.loading = true
      oaExaminePrintTemplatePreviewAPI({
        type: this.perviewType,
        content: this.content
      })
        .then(res => {
          this.loading = false
          const data = res.data
          const iframeUrl = `/crmPrint/preview.pdf?type=1&key=${data}`
          downloadFileAPI(iframeUrl).then(res => {
            this.iframeUrl = window.URL.createObjectURL(res.data)
          }).catch(() => {})

          this.srcData = data
          this.isPreview = true
        })
        .catch(() => {
          this.loading = false
        })
    },

    /**
     *保存打印记录
     */
    // savePrintRecord() {
    //   if (this.templateId && this.typeId) {
    //     printSaveRecordAPI({
    //       templateId: this.templateId,
    //       typeId: this.typeId,
    //       recordContent: this.content
    //     })
    //       .then(res => {
    //       })
    //       .catch(() => {
    //       })
    //   }
    // },

    hidenView() {
      this.$emit('close')
    },

    /** 预览页面逻辑 */

    handleClick(type) {
      if (type == 'goback') {
        this.isPreview = false
      } else if (type == 'print') {
        document.getElementById('wkPrint').contentWindow.print() // 调用浏览器的打印功能打印指定区域
        // this.savePrintRecord()
      } else if (type == 'download') {
        if (this.srcData) {
          var ext = this.perviewType
          const path = this.srcData
          var data = {
            key: path,
            type: ext === 'word' ? 2 : 1
          }
          ext = ext === 'word' ? 'doc' : 'pdf'
          crmFileDownByPathAPI(data).then(res => {
            downloadFileWithBuffer(res.data, `文档.${ext}`)
          }).catch(() => {})
        }
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.wk-print-container {
  .el-header {
    position: relative;
    z-index: 1;
    display: flex;
    align-items: center;
    height: 60px;
    padding: 0 70px;
    background-color: white;
    box-shadow: 0 1px 2px #dbdbdb;

    .wk-help-tips {
      margin-left: 8px;
    }

    .select-label {
      margin-right: 15px;
    }

    .el-select + .select-label {
      margin-left: 30px;
    }
  }

  .preview-button {
    position: absolute;
    top: 16px;
    right: 70px;
  }

  .el-main {
    padding: 0;
  }

  &.is-perview {
    .el-header {
      display: block;
      line-height: 60px;
      text-align: right;
    }
  }
}

.main-container {
  display: flex;
  flex-direction: column;
  height: 100%;

  .main-tips {
    margin: 20px 0;
    font-size: 13px;
    color: #bfbfbf;
    text-align: center;
  }

  .main-content {
    flex: 1;
    width: 66%;
    margin: 0 auto;
  }
}

</style>
